import { observable, action, isObservable } from 'mobx';
import { Modal, message } from 'antd';
import { WeaTableNew, WeaForm } from 'comsMobx';
import AlertModal from '../public/AlertModal';
import * as settingUtils from '../util/settingUtils';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const confirm = Modal.confirm;

export default class commonStore {
    constructor() {
    }

    @observable defaultid = '';

    @observable curOperatedRows = [];
    @observable curOperatedKeys = '';
    @observable buttonDisabled = false;

    @observable isDiaOpened = false;

    // 邮件设置每个tab的主要表格的sessionkey，不是弹框中的表格的sessionkey
    @observable mainSessionkey = '';
    @observable mainTableDatas = [];


    @action
    setParamsState = (params = {}) => {
      Object.keys(params).forEach((key) => {
        this[key] = params[key];
      });
    }

    @action getTableData = (tableStore, interfaceOfGetTableData) => {
        interfaceOfGetTableData().then(action('getTableDataSucc', (data) => {
            this.mainSessionkey = data.sessionkey;
            tableStore.getDatas(data.sessionkey);
        }));
    }

    // 当需要后端接口才能获取到val，那就要传入interfaceOfGetVal，而不传入val,此时可能需要传入interfaceBehavior
    // 当不需要后端接口才能获取到val，那就不需要传入interfaceOfGetVal，而需要传入val
    // 当attrType为map时，val得为一个对象，对象的每个属性对应map的属性，属性值对应map相应的属性值
    @action setStoreAttr = ({ attr, interfaceOfGetVal, interfaceBehavior, val, callback, attrType = 'normal' }) => {
        if (interfaceOfGetVal) {
            interfaceOfGetVal().then(action('GetValSuc', (data) => {
                switch (interfaceBehavior) {
                    case 'getTopTabs':
                        val = data.grouptinfo;
                        break;

                    case 'setDefaulId':
                        val = data;
                        break;
                }

                if (attrType === 'normal') {
                    this[attr] = val;
                } else if (attrType === 'map') {
                    this[attr].merge(val);
                }

                callback && callback(val);
            }));
        } else {
            if (attrType === 'normal') {
                this[attr] = val;
            } else if (attrType === 'map') {
                this[attr].merge(val);
            }

            callback && callback(val);
        }
    }


    @action initWeaForm = ({ compStore, weaformStoreName, interfaceOfGetCon, interfaceParams = {}, conditionAttrName, isConGetted, afterGetCon }) => {
        if (isConGetted === true) {
            compStore[weaformStoreName] = new WeaForm();
            compStore[weaformStoreName].initFormFields(compStore[conditionAttrName]);
        } else {
            interfaceOfGetCon(interfaceParams).then((data) => {
                compStore[weaformStoreName] = new WeaForm();
                compStore[conditionAttrName] = data.conditioninfo;
                compStore[weaformStoreName].initFormFields(compStore[conditionAttrName]);
                afterGetCon && afterGetCon(data);
            });
        }
    };


    /**
     * 应用场景：点添加按钮时会用到的handler
     * 做的事情：设置弹窗的visible为true，reinit弹窗里的wea-formsss，设置弹窗的title，可选的其他动作(如清空富文本、)放入callback中去
     *
     * @param confsOfInitweaForms:这是一个数组，每个数组元素为一个对象，对象的数据格式同要传给initWeaForm action的参数形式
     * @param attrOfControlVisible: 字符串，store中用于控制弹窗是否显示的属性
     * @param cb 回调，点击添加按钮想要做的其他事情在此定义
     * @param attrOfDiaTitle : 字符串，store中用于控制弹窗title的属性
     * @param diaTitle：字符串，用于控制弹窗的title
     * @param ifChgTitle:在打开弹窗是是否同时改变弹窗的title
     */
    @action onAddBtnClick = ({ confsOfInitweaForms, attrOfControlVisible, cb, attrOfDiaTitle, diaTitle }) => {
        confsOfInitweaForms.forEach((elem) => {
            this.initWeaForm(elem);
        });
        this.setStoreAttr({ attr: attrOfControlVisible, val: true });

        this.setStoreAttr({ attr: attrOfDiaTitle, val: diaTitle });

        cb && cb();
    };


    /**
     * 应用场景：点弹窗中的关闭按钮或x符号时会用到的handler
     * 做的事情：设置弹窗的visible为false，reinit弹窗里的wea-formsss，可选的其他动作放入callback中去
     *
     * @param confsOfInitweaForms:这是一个数组，每个数组元素为一个对象，对象的数据格式同要传给initWeaForm action的参数形式
     * @param attrOfControlVisible: 字符串，store中用于控制弹窗是否显示的属性
     * @param cb 回调，点击添加按钮想要做的其他事情在此定义
     */
    @action onClsDiaClick = ({ confsOfInitweaForms, attrOfControlVisible, cb }) => {
        confsOfInitweaForms.forEach((elem) => {
            this.initWeaForm(elem);
        });
        this.setStoreAttr({ attr: attrOfControlVisible, val: false });
        cb && cb();
    }

    /**
     * 该方法适合于编辑返显
     * @param weaformStoreName:字符串，表示store中那个指向某wea-form的属性
     * @param attrOfControlVisible
     * @param cb
     * @param editInfoData 若isEditInfoGetted=true，要传入相应的数据
     * @param attrOfDiaTitle
     * @param diaTitle
     * @param compStore:一个组件的store对象
     * @param showEditInfoFn:接受从后台获取到的data对象，然后这个方法用于定义如何把未编辑前的信息显示给用户看
     */
    @action onEditBtnClick = ({ interfaceParams, interfaceOfGetEditInfo, editInfoData, ifOpenDia = true, isEditInfoGetted = false, attrOfControlVisible, cb, attrOfDiaTitle, diaTitle, compStore, showEditInfoFn }) => {
        if (!isEditInfoGetted) {
            interfaceOfGetEditInfo(interfaceParams).then((data) => {
                showEditInfoFn(data);
                // compStore[weaformStoreName].updateFields(data, true, true);
                if (ifOpenDia) {
                    compStore[attrOfControlVisible] = true;
                    compStore[attrOfDiaTitle] = diaTitle;
                }


                cb && cb();
            });
        } else {
            showEditInfoFn(editInfoData);
            // compStore[weaformStoreName].updateFields(data, true, true);
            if (ifOpenDia) {
                compStore[attrOfControlVisible] = true;
                compStore[attrOfDiaTitle] = diaTitle;
            }
            cb && cb();
        }
    };

    /**
     * 点击保存按钮要做的事情，
     * (是否为新建编辑的区别是要多传一个id)
     *取到所有的wea-forms的data，还有一些其他可能变的(可能是富文本、可能是电子签名这样复杂的)数据统一存放在一个叫otherparams的对象中，
     * {...weaformdata,...otherParams}这种形式传给后台，传递成功后根据场景是否关闭弹窗，然后是否刷新table数据
     *
     * @param saveAction
     * @param interfaceOfSave
     * @param weaformStoreNames
     * @param otherParams
     * @param ifClsDia
     * @param attrOfControlVisible
     * @param ifReloadTableData
     * @param tableStore
     * @param interfaceOfGetTableData
     * @param beforeReqInterface
     * @param afterReqInterface
     * @param needCheckButton 是否控制按钮禁用，防止重复点击
     * @param falseCanNoColse 失败后是否要关闭当前弹框
     */
    @action onSaveBtnClick = ({ saveAction, interfaceOfSave, weaformStoreNames, otherParams = {}, ifClsDia = false, attrOfControlVisible, ifReloadTableData = false, tableStore, interfaceOfGetTableData, beforeReqInterface, afterReqInterface, needCheckButton, falseCanNoColse }) => {
        if (needCheckButton) {
            this.setParamsState({ buttonDisabled: true });
        }
        let weaFormParams = {};
        let params = {};
        let isValid = true;
        let needrefish = true;
        // 这边取到所有的wea-form的参数并一起放入到weaFormParams对象中
        weaformStoreNames.forEach((weaformStoreName) => {
            this[weaformStoreName].validate().then((f) => {
                if (!f.isValid) {
                    isValid = false;
                    if (needCheckButton) {
                        this.setParamsState({ buttonDisabled: false });
                    }
                }
            });
        });

        // 因为上面检测必填项的操作是异步的，所以这里弄了个定时器
        setTimeout(action(() => {
            if (isValid) {
                weaformStoreNames.forEach((weaformStoreName) => {
                    weaFormParams = { ...weaFormParams, ...this[weaformStoreName].getFormParams() };
                });

                // if (saveAction === 'newSave') {
                //     params = {...weaFormParams, ...otherParams, };
                // } else if (saveAction === 'editSave') {
                //     params = {...weaFormParams, ...otherParams, id: id};
                // }

                params = { ...weaFormParams, ...otherParams };

                beforeReqInterface && beforeReqInterface();
                interfaceOfSave(params).then((data) => {
                    const { flag, status } = data;
                    settingUtils.messagesOfoperateResult({
                        SuccOrFailObj: { flag },
                        succText: getLabel(83551, '保存成功'),
                        success: () => {
                        },
                        failText: data.hasOwnProperty('message') ? data.message : getLabel(21809, '保存失败'),
                    });

                    // 此处共用页面太多，不敢随意优化，如果页面全部理清，start--起到end结束能合并
                    if (ifClsDia) {
                        if ((falseCanNoColse || data.message === 'repeat') && !data.flag) {
                            needrefish = false;
                        } else {
                            this[attrOfControlVisible] = false;
                        }
                    }
                    if (falseCanNoColse || data.message === 'repeat') {
                        // 接口执行状态的返回标志可能不同，请依次兼容
                        if (!data.flag) {
                            needrefish = false;
                            this[attrOfControlVisible] = true;
                        }
                    }
                    // -----end

                    if (ifReloadTableData && needrefish) {
                        this.getTableData(tableStore, interfaceOfGetTableData);
                    }

                    afterReqInterface && afterReqInterface(data);
                });
            } else {
                AlertModal('warning', getLabel(384379, '您还有必填信息未填'));
            }
        }), 300);
    };

    /* deleting: 删除邮件账号时的轻提示 */
    @action onDelBtnClick = ({ interfaceOfDel, interfaceParams, tableStore, interfaceOfGetTableData, delWarnText = getLabel(15097, '确定要删除吗？'), afterReqInterface, deleting }) => {
        confirm({
            title: getLabel(131329, '信息确认'),
            content: (<span>{delWarnText}</span>),
            okText: getLabel(826, '确定'),
            onOk: () => {
              deleting && message.loading(`${getLabel('19611', '处理中')}...`, 0);
                interfaceOfDel(interfaceParams).then((data) => {
                    const { flag, status } = data;
                    settingUtils.messagesOfoperateResult({
                        SuccOrFailObj: { flag },
                        succText: getLabel(20461, '删除成功'),
                        success: () => {
                            this.getTableData(tableStore, interfaceOfGetTableData);
                            afterReqInterface && afterReqInterface(data);
                        },
                        failText: data.hasOwnProperty('message') ? data.message : getLabel(20462, '删除失败'),
                      });
                      deleting && message.destroy();
                });
            },
            onCancel() {},
        });
    };
}
